package com.example.demo.controller.music;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.example.demo.pojo.Music;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * http测试
 *
 * @author yzh
 * @date 2023/03/31
 */
@Controller
@RequestMapping("/kuwo")
public class kuwo {
    private static String kw_token;
    private static String MusicName;

    public static void main(String[] args) throws IOException {



       /* String data = Get_playlist_music("3159088422");
        JSONArray array = JSON.parseArray(data);
        String regEx="[`~!@#$%^&*+=|{}':;',//[//].<>/?~！@#￥%……&*——+|{}【】‘；：”“’。，、？]";
        Pattern pattern = Pattern.compile(regEx);

        long l = System.currentTimeMillis();
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = array.getJSONObject(i);
            String url = GetMusicUrl(kw_token, object.getString("rid"));
            Matcher matcher = pattern.matcher(object.getString("name"));
            String path = "D:\\test\\" + matcher.replaceAll("") + ".mp3";

            Thread thread = new Thread(new download(url, path));
            thread.start();
        }
        System.out.println(System.currentTimeMillis() - l + "ms");

        search("晴天","1");*/


    }

    /*@PostConstruct
    public void init(){
        kw_token = HttpRequest.get("http://www.kuwo.cn/")
                .timeout(20000)//超时，毫秒
                .execute().getCookieValue("kw_token");

    }*/

    //modelAttribute:该controller中每个@RequestMapping方法执行前都要先执行@ModelAttribute注解下的方法
    @ModelAttribute
    public static void gettoken() {
        kw_token = HttpRequest.get("http://www.kuwo.cn/")
                .timeout(20000)//超时，毫秒
                .execute().getCookieValue("kw_token");
    }

    /**
     * 搜索
     *
     * @param keyword 关键字
     * @param type    类型
     * @return {@link String}
     */
    @RequestMapping("/search")
    @ResponseBody
    public static String search(String keyword, String type) {
        String searchtype = "";
        //1:歌曲搜索 2:歌单搜索
        if (type.equals("1")) {
            searchtype = "searchMusicBykeyWord";
        } else if (type.equals("2")) {
            searchtype = "searchPlayListBykeyWord";
        }

        String url = "https://www.kuwo.cn/api/www/search/" + searchtype + "?key=" + keyword + "&pn=1&rn=20";
        String s = HttpRequest.get(url)
                .timeout(20000)//超时，毫秒
                .header("csrf", kw_token)
                .header("Referer", "http://www.kuwo.cn/search/playlist")
                .cookie("kw_token=" + kw_token)
                .execute().body();
        return s;
    }


    /**
     * 获取歌单歌曲列表
     *
     * @param id id
     * @return {@link String}
     */
    @RequestMapping("/Get_playlist_music")
    public static String Get_playlist_music(String id) {
        String url = "";
        ArrayList<String> list = new ArrayList<>();

        for (int i = 1; i < 10; i++) {
            url = "http://www.kuwo.cn/api/www/playlist/playListInfo?pid=" + id + "&pn=" + i + "&rn=20&httpsStatus=1";
            String s = HttpRequest.get(url)
                    .timeout(20000)//超时，毫秒
                    .header("csrf", kw_token)
                    .header("Referer", "http://www.kuwo.cn/search/playlist")
                    .cookie("kw_token=" + kw_token)
                    .execute().body();

            String data = JSON.parseObject(JSON.parseObject(s).get("data").toString()).get("musicList").toString();
            String musicList = data.substring(1, data.length() - 1);
            if (musicList.length() == 0) {
                break;
            } else {
                list.add(musicList);
            }
        }
        return list.toString();
    }


    /**
     * 获取音乐网址
     *
     * @param id id
     * @return {@link String}
     */
    @RequestMapping("/GetMusicUrl")
    @ResponseBody
    public static String GetMusicUrl(String id) {
        String s = HttpRequest.get("https://www.kuwo.cn/api/v1/www/music/playUrl?mid=" + id + "&type=convert_url3&br=128kmp3")
                .timeout(20000)//超时，毫秒
                .header("csrf", kw_token)
                .header("Referer", "http://www.kuwo.cn/search/playlist")
                .cookie("kw_token=" + kw_token)
                .execute().body();
        String url = JSON.parseObject(JSON.parseObject(s).get("data").toString()).get("url").toString();

        return url;
    }


    /**
     * 获得排名数据
     *
     * @param id id
     * @return {@link String}
     * 飙升榜：93；新歌榜：17；热歌：16；抖音：158；dj：176
     */
    @RequestMapping("/GetRankData")
    @ResponseBody
    public static List<Music> GetRankData(String id) {
        ArrayList<Music> list = new ArrayList<>();
        String s = HttpRequest.get("http://www.kuwo.cn/api/www/bang/bang/musicList?bangId=" + id + "&pn=1&rn=20&httpsStatus=1")
                .timeout(20000)//超时，毫秒
                .header("csrf", kw_token)
                .header("Referer", "http://www.kuwo.cn/search/playlist")
                .cookie("kw_token=" + kw_token)
                .execute().body();

        JSONArray jsonArray = JSON.parseArray(JSON.parseObject(JSON.parseObject(s).get("data").toString()).get("musicList").toString());
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = JSON.parseObject(jsonArray.getString(i));
            /*String rid = GetMusicUrl(jsonObject.getString("rid"));*/
            Music music = new Music();
            music.setName(jsonObject.get("name"));
            music.setArtist(jsonObject.get("artist"));
            music.setAlbum(jsonObject.get("album"));
            music.setTime(jsonObject.get("songTimeMinutes"));
            music.setPlayurl("https://ll-sycdn.kuwo.cn/97975f6801a60b2a83b36845f6c63a85/649be2c7/resource/n1/98/26/1755647252.mp3");
            list.add(music);

        }
        return list;
    }

}
